package factory_pattern.simple_factory.connection_impl;

import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpConnection implements NetworkConnection {
    private final String host;
    private final int port;
    private DatagramSocket socket;
    private InetAddress targetAddr;

    public UdpConnection(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public boolean connect() {
        // UDP无连接，仅初始化Socket和目标地址
        try {
            socket = new DatagramSocket();
            targetAddr = InetAddress.getByName(host);
            System.out.printf("[UDP] 初始化成功（目标：%s:%d）%n", host, port);
            return true;
        } catch (Exception e) {
            System.out.printf("[UDP] 初始化失败：%s%n", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendData(byte[] data) {
        if (socket == null || targetAddr == null) {
            System.out.println("[UDP] Socket未初始化，无法发送");
            return false;
        }
        try {
            socket.send(new java.net.DatagramPacket(data, data.length, targetAddr, port));
            System.out.printf("[UDP] 发送成功：%d 字节（目标：%s:%d）%n", data.length, host, port);
            return true;
        } catch (Exception e) {
            System.out.printf("[UDP] 发送失败：%s%n", e.getMessage());
            return false;
        }
    }

    @Override
    public void close() {
        if (socket != null) {
            socket.close();
            System.out.println("[UDP] Socket关闭");
            socket = null;
            targetAddr = null;
        }
    }
}